package dataDAOImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;


import dataConnector.Connector;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.IOperatorDAO;
import dataDTO.OperatorDTO;

public class MySQLOperatorDAO implements IOperatorDAO {
	public OperatorDTO getOperator(int oprId) throws DALException {
		ResultSet rs = Connector.doQuery("SELECT * FROM operatoer WHERE opr_id = " + oprId);
	    try {
	    	if (!rs.first()) throw new DALException("The operator " + oprId + " dont exist");
	    	return new OperatorDTO (rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7));
	    }
	    catch (SQLException e) {throw new DALException(e); }
		
	}
	
	public void createOperator(OperatorDTO opr) throws DALException {		
			Connector.doUpdate(
				"INSERT INTO operatoer(opr_id, opr_navn, ini, cpr, password, status, rolle) VALUES " +
				"(" + opr.getOprId() + ", '" + opr.getOprName() + "', '" + opr.getIni() + "', '" + 
				opr.getCpr() + "', '" + opr.getPassword() + "', '" + opr.getStatus() + "', '" + opr.getRole() + "')"
			);
	}
	
	public void updateOperator(OperatorDTO opr) throws DALException {
		Connector.doUpdate(
				"UPDATE operatoer SET  opr_navn = '" + opr.getOprName() + "', ini =  '" + opr.getIni() + 
				"', cpr = '" + opr.getCpr() + "', password = '" + opr.getPassword() + "', status = '" + opr.getStatus() + "', rolle = '" + 
						opr.getRole() + "' WHERE opr_id = " + opr.getOprId()
		);
	}
	
	public List<OperatorDTO> getOperatorList() throws DALException {
		List<OperatorDTO> list = new ArrayList<OperatorDTO>();
		ResultSet rs = Connector.doQuery("SELECT * FROM operatoer");
		try
		{
			while (rs.next()) 
			{
				list.add(new OperatorDTO(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7)));
			}
		}
		catch (SQLException e) { throw new DALException(e); }
		return list;
	}
		
}
	
